package com.cjb.base.controller;

import com.cjb.base.domain.User;
import com.cjb.base.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService userService;


    @GetMapping(name = "返回用户的登陆的界面")
    public String toLogin(){
        return "login";
    }

   @GetMapping(value="/dologin",name = "get方式提交用户的信息")
   public String dologin(){
        return "login";
   }



    @PostMapping(value="/dologin",name = "用户登录信息")
    @ResponseBody
    public ModelAndView dologin(String loginName,String password){
        ModelAndView mv = new ModelAndView();
        User user = userService.getByLoginName(loginName);
        if(user==null||!user.getPassword().equals(password)){
            mv.addObject("messages","用户不存在");
            mv.setViewName("login");
            return mv;
        }
            //创建subject
            Subject subject = SecurityUtils.getSubject();

            AuthenticationToken token=new UsernamePasswordToken(user.getLoginName(),user.getPassword());

            subject.login(token);

            mv.addObject("user",user);

             //TODO 处理用户登录之后，跳转到index页面的刷新问题

            mv.setViewName("index");

            return mv;
        }



    @GetMapping(value = "/logout",name = "当前用户退出登录")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }


}
